package edu.ccut.saturn.basecomponent.database.impl.hsql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.component.IDataInfo;
import edu.ccut.saturn.component.IDataItem;
import edu.ccut.saturn.component.SaturnData;

/**
 * 经refactory后生成的新类,作用:针对sqlserver将生成的主键在SaturnData重新赋值
 * 
 * @author zjh
 * 
 */
public class HsqlSetPrimaryKeyInSaturnData {
	
	private static final String LAST_INSERT_ID = "CALL IDENTITY()";

	private static final int PRIMARY_KEY_COLUMN_NUMBER = 1;

	/**
	 * @author zjh
	 * @param connection
	 *            数据库连接对象
	 * @param saturnSQL
	 *            saturnSQL对象
	 */
	public static void setPrimaryKeyValue(Connection connection,
			ISaturnSQL saturnSQL) {

		if (connection != null && saturnSQL != null) {
			ResultSet resultSet = null;
			Statement statement = null;
			try {
				statement = connection.createStatement();
				resultSet = statement.executeQuery(LAST_INSERT_ID);
				if (resultSet.next()) {
					int currPrimaryKeyValue = resultSet
							.getInt(PRIMARY_KEY_COLUMN_NUMBER);
					SaturnData saturnData = saturnSQL.getSaturnData();
					IDataInfo dataInfo = saturnData.getSaturnDataInfo();
					for (String key : dataInfo.keySet()) {
						IDataItem dataItem = dataInfo.getDataItem(key);
						if ("true".equalsIgnoreCase(dataItem.getIsPrimaryKey())) {
							saturnData.set(key, currPrimaryKeyValue);
							System.out.println(key+"=="+currPrimaryKeyValue);
							break;
						}
					}
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (statement != null) {
					try {
						statement.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				if (resultSet != null) {
					try {
						resultSet.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
